<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">管理员管理</h1>
      </div>
    </div>

    <!-- 管理员列表 -->
    <el-card shadow="never">
      <div class="toolbar">
        <el-input v-model="keyword" placeholder="搜索用户名/邮箱/手机号" clearable style="max-width: 260px" />
        <el-button type="success" @click="openAddDialog">
          <el-icon><Plus /></el-icon>
          新增管理员
        </el-button>
      </div>

      <el-table :data="filtered" :loading="adminStore.loading" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :size="32" :src="row.avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机" width="140" />
        <el-table-column prop="role" label="角色" width="100" />
        <el-table-column prop="status" label="状态" width="100" />
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button text type="primary" @click="openEdit(row)">编辑</el-button>
            <el-button text type="danger" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pager">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="adminStore.total"
          :page-size="adminStore.queryParams.limit"
          v-model:current-page="adminStore.queryParams.page"
          @current-change="adminStore.loadAdminList"
        />
      </div>
    </el-card>

    <!-- 新增管理员对话框 -->
    <el-dialog v-model="addVisible" title="新增管理员" width="520px">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="88px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="超级管理员" :value="1" />
            <el-option label="管理员" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="handleAddAvatarUpload"
            accept="image/*"
          >
            <img v-if="addForm.avatar" :src="addForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addVisible=false">取消</el-button>
        <el-button type="primary" @click="submitAdd" :loading="adminStore.loading">保存</el-button>
      </template>
    </el-dialog>

    <!-- 编辑管理员对话框 -->
    <el-dialog v-model="editVisible" title="编辑管理员" width="520px">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="88px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="handleEditAvatarUpload"
            accept="image/*"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible=false">取消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="adminStore.loading">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useAdminStore } from '@/stores/admin/adminStore'

// 状态定义
const adminStore = useAdminStore()
const keyword = ref('')
const addVisible = ref(false)
const editVisible = ref(false)

// 表单引用
const addFormRef = ref()
const editFormRef = ref()

// 新增表单数据
const addForm = reactive({
  username: '',
  password: '',
  email: '',
  phone: '',
  role: 2,
  status: 1,
  avatar: ''
})

// 编辑表单数据
const editForm = reactive({ 
  id: null, 
  username: '', 
  email: '', 
  phone: '', 
  avatar: '' 
})

// 新增表单验证规则
const addFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '2-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '6-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^\d{11}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 编辑表单验证规则
const editFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^\d{11}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
  ]
}

// 过滤后的数据
const filtered = computed(() => {
  const k = keyword.value.trim().toLowerCase()
  if (!k) return adminStore.adminList
  return adminStore.adminList.filter((u) =>
    [u.username, u.email, u.phone].some(v => String(v || '').toLowerCase().includes(k))
  )
})

// 打开新增对话框
const openAddDialog = () => {
  resetAddForm()
  addVisible.value = true
}

// 重置新增表单
const resetAddForm = () => {
  Object.assign(addForm, {
    username: '',
    password: '',
    email: '',
    phone: '',
    role: 2,
    status: 1,
    avatar: ''
  })
  if (addFormRef.value) {
    addFormRef.value.clearValidate()
  }
}

// 提交新增
const submitAdd = async () => {
  if (!addFormRef.value) return
  
  const valid = await addFormRef.value.validate()
  if (!valid) return
  
  try {
    // 创建FormData支持文件上传
    const formData = new FormData()
    Object.keys(addForm).forEach(key => {
      if (addForm[key] !== null && addForm[key] !== undefined && addForm[key] !== '') {
        formData.append(key, addForm[key])
      }
    })
    
    // 如果有头像文件，添加到FormData
    if (addForm.avatarFile) {
      formData.append('avatar', addForm.avatarFile)
    }
    
    const result = await adminStore.addAdmin(formData)
    
    ElMessage.success('管理员创建成功')
    
    addVisible.value = false
  } catch (error) {
    // 错误处理由adminStore.addAdmin内部处理
  }
}

// 打开编辑对话框
const openEdit = (row) => {
  Object.assign(editForm, { 
    id: row.id, 
    username: row.username, 
    email: row.email, 
    phone: row.phone, 
    avatar: row.avatar 
  })
  adminStore.currentAdmin = row
  editVisible.value = true
}

// 新增头像上传
const handleAddAvatarUpload = async (file) => {
  // 文件类型验证
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }

  // 文件大小验证 (2MB)
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 新增用户时，先做本地预览，等用户创建成功后再上传头像
  const reader = new FileReader()
  reader.onload = (e) => {
    addForm.avatar = e.target.result
  }
  reader.readAsDataURL(file)
  addForm.avatarFile = file
  return false
}

// 编辑头像上传
const handleEditAvatarUpload = async (file) => {
  // 文件类型验证
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }

  // 文件大小验证 (2MB)
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 头像预览（实际上传在保存时处理）
  const reader = new FileReader()
  reader.onload = (e) => {
    editForm.avatar = e.target.result
  }
  reader.readAsDataURL(file)
  
  // 保存文件对象供后续使用
  editForm.avatarFile = file
  
  return false
}

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return
  
  const valid = await editFormRef.value.validate()
  if (!valid) return
  
  try {
    // 创建FormData支持文件上传
    const formData = new FormData()
    Object.keys(editForm).forEach(key => {
      if (editForm[key] !== null && editForm[key] !== undefined && editForm[key] !== '') {
        formData.append(key, editForm[key])
      }
    })
    
    // 如果有头像文件，添加到FormData
    if (editForm.avatarFile) {
      formData.append('avatar', editForm.avatarFile)
    }
    
    await adminStore.editAdmin(formData)
    editVisible.value = false
  } catch (error) {
    // 错误处理由adminStore.editAdmin内部处理
  }
}

// 删除管理员
const remove = async (id) => {
  await adminStore.deleteAdmin(id)
}

// 生命周期
onMounted(() => {
  adminStore.loadAdminList()
})
</script>

<style scoped lang="scss">
.page-container { padding: 16px; }
.page-header { margin-bottom: 12px; }
.toolbar { display: flex; gap: 12px; margin-bottom: 12px; }
.pager { margin-top: 12px; display: flex; justify-content: flex-end; }


.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
    
    &:hover {
      border-color: #409eff;
    }
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
  }
}
</style>